import React, { useState,  } from "react";
import { useNavigate } from "react-router-dom";
import { Avatar, Badge, Button, Progress, Cell, Dialog, Input, Toast, Popup } from "@nutui/nutui-react";
import { useDispatch, useSelector } from "react-redux";
import { logoutUser, updateUserInfo } from "@/store/actions/userActions";
import { api } from "@/api/api";
import {
  Heart,
  Star,
  Setting,
  Clock,
  Edit,
  Wallet,
  Service,
  Cart,
  ArrowTransfer,
  Photograph,
  ArrowRight
} from "@nutui/icons-react";
import "./index.less";

const UserView = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const userInfo = useSelector((state) => state.user.userInfo);
  const [showLogoutDialog, setShowLogoutDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [editForm, setEditForm] = useState({
    nickName: userInfo?.name || "",
    avatar: userInfo?.avatar || "",
  });
  const [isUpdating, setIsUpdating] = useState(false);

  // 处理退出登录
  const handleLogout = () => {
    setShowLogoutDialog(true);
  };

  // 确认退出登录
  const confirmLogout = () => {
    dispatch(logoutUser());
    setShowLogoutDialog(false);
    navigate('/login');
  };

  // 处理编辑用户信息
  const handleEditUser = () => {
    setEditForm({
      nickName: userInfo?.name || "",
      avatar: userInfo?.avatar || "",
    });
    setShowEditDialog(true);
  };

  // 处理头像选择
  const handleAvatarSelect = () => {
    // 微信环境
    const isWechat = /micromessenger/i.test(navigator.userAgent);
    
    console.log('选择头像 - 当前环境:', isWechat ? '微信' : '普通浏览器');
    
    // 在真实微信环境中，直接使用文件选择器更稳定
    // wx.chooseImage 在真实环境中容易因为域名配置问题失败
    // eslint-disable-next-line no-undef
    if (false && isWechat && typeof wx !== 'undefined' && wx.chooseImage) {
      // eslint-disable-next-line no-undef
      wx.chooseImage({
        count: 1, // 最多可以选择的图片张数
        sizeType: ['compressed'], // 指定是原图还是压缩图
        sourceType: ['album', 'camera'], // 指定来源是相册还是相机
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          setEditForm(prev => ({
            ...prev,
            avatar: tempFilePath
          }));
          // Toast.show('头像选择成功');
        },
        fail: (error) => {
          let errorMsg = '选择图片失败，请重试';
          
          if (error.errMsg) {
            if (error.errMsg.includes('permission value is offline verifying')) {
              errorMsg = '微信权限验证失败，将使用备用方案';
              // 文件选择器
              setTimeout(() => {
                const input = document.createElement('input');
                input.type = 'file';
                input.accept = 'image/*';
                input.onchange = (e) => {
                  const file = e.target.files[0];
                  if (file) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                      const base64Data = e.target.result;
                      setEditForm(prev => ({
                        ...prev,
                        avatar: base64Data
                      }));
                      Toast.show('头像选择成功');
                    };
                    reader.readAsDataURL(file);
                  }
                };
                input.click();
              }, 1000);
            } else if (error.errMsg.includes('cancel')) {
              errorMsg = '已取消选择';
            } else if (error.errMsg.includes('permission')) {
              errorMsg = '没有相册权限，请在设置中开启';
            } else if (error.errMsg.includes('config')) {
              errorMsg = '微信功能未配置，请刷新页面重试';
            }
          }
          // Toast.show(errorMsg);
        }
      });
    } else {
      // 使用HTML5文件选择器（兼容所有环境）
      console.log('使用文件选择器');
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = 'image/*';
      input.onchange = (e) => {
        const file = e.target.files[0];
        if (file) {
          console.log('选择的文件:', file.name, '大小:', file.size, 'bytes');
          
          if (file.size > 5 * 1024 * 1024) {
            Toast.show('图片大小不能超过5MB');
            return;
          }
          
          const reader = new FileReader();
          reader.onload = (e) => {
            const base64Data = e.target.result;
            console.log('图片转换成功，base64长度:', base64Data.length);
            setEditForm(prev => ({
              ...prev,
              avatar: base64Data 
            }));
            Toast.show('图片选择成功');
          };
          reader.onerror = (err) => {
            console.error('图片读取失败:', err);
            Toast.show('图片读取失败，请重试');
          };
          reader.readAsDataURL(file);
        }
      };
      input.click();
    }
  };

  // 处理表单输入变化
  const handleFormChange = (field, value) => {
    setEditForm(prev => ({
      ...prev,
      [field]: value
    }));
  };

  // 上传头像图片
  const uploadAvatar = async (avatarData) => {
    try {
      let fileToUpload;
      
      if (avatarData.startsWith('data:image/')) {
        const response = await fetch(avatarData);
        const blob = await response.blob();
        fileToUpload = new File([blob], 'avatar.jpg', { type: 'image/jpeg' });
      } else if (avatarData.startsWith('wxfile://')) {
        console.log('微信临时文件路径，尝试直接上传:', avatarData);
        fileToUpload = avatarData;
      } else {
        return avatarData;
      }
      console.log('开始上传头像...');
      const uploadResponse = await api.uploadImage(fileToUpload);
      console.log('上传响应:', uploadResponse);
      
      if (uploadResponse.code === 200) {
        let avatarUrl = uploadResponse.data?.url || uploadResponse.data?.path || uploadResponse.data;
        console.log('头像上传成功，URL:', avatarUrl);
        return avatarUrl;
      } else {
        const errorMsg = uploadResponse.message || uploadResponse.msg || '上传失败';
        console.error('上传失败:', errorMsg);
        throw new Error(errorMsg);
      }
    } catch (error) {
      console.error('上传头像异常:', error);
      if (error.response) {
        console.error('错误响应:', error.response);
      }
      throw error;
    }
  };

  // 确认更新用户信息
  const confirmUpdateUser = async () => {
    if (!editForm.nickName.trim()) {
      Toast.show("请输入用户名称");
      return;
    }

    const userId =  userInfo?.userId
    
    if (!userId) {
      Toast.show("用户信息不完整，请重新登录");
      return;
    }

    setIsUpdating(true);
    try {
      let avatarUrl = editForm.avatar;
      
      if (editForm.avatar && (editForm.avatar.startsWith('data:image/') || editForm.avatar.startsWith('wxfile://'))) {
        avatarUrl = await uploadAvatar(editForm.avatar);
      }

      const updateData = {
        id: userId,
        nickName: editForm.nickName,
        avatar: avatarUrl
      };
      
      const response = await api.updateWxUserInfo(updateData);
      
      const updatedUserInfo = {
        ...userInfo,
        nickName: editForm.nickName,
        avatar: avatarUrl
      };
      
      dispatch(updateUserInfo({
        name: editForm.nickName,
        avatar: avatarUrl
      }));
      
      localStorage.setItem("user_info", JSON.stringify(updatedUserInfo));
      
      Toast.show("更新成功");
      setShowEditDialog(false);
    } catch (error) {
      const errorMessage = error.response?.data?.message || error.message || "更新失败，请重试";
      Toast.show(errorMessage);
    } finally {
      setIsUpdating(false);
    }
  };

  const orderStatus = [
    { label: "待付款", value: "0", icon: <Cart />, color: "#ff6b35", payStatus: "0" },
    { label: "已支付", value: "1", icon: <Clock />, color: "#28a745", payStatus: "1" },
    { label: "退款中", value: "2", icon: <Star />, color: "#ffc107", payStatus: "2" },
    { label: "已退款", value: "3", icon: <ArrowTransfer />, color: "#6c757d", payStatus: "3" },
  ];

  // 统计数据
  const statsData = [
    { label: "积分", value: "1,280", icon: <Star />, color: "#ff6b6b" },
    { label: "订单", value: "23", icon: <Clock />, color: "#4ecdc4" },
    { label: "收藏", value: "156", icon: <Heart />, color: "#45b7d1" },
    { label: "优惠券", value: "5", icon: <Clock />, color: "#96ceb4" },
  ];

  // 功能菜单数据
  const menuItems = [
    {
      title: "我的收藏",
      icon: <Heart />,
      path: "",
    },
    {
      title: "我的评价",
      icon: <Star />,
      path: "",
    },
    {
      title: "我的钱包",
      icon: <Wallet />,
      path: "",
    },
    {
      title: "客服中心",
      icon: <Service />,
      path: "",
    },
    {
      title: "帮助中心",
      icon: <Setting />,
      path: "",
    },
    {
      title: "设置",
      icon: <Setting />,
      path: "/settings",
    },
  ];

  // 处理查看全部订单
  const handleViewAllOrders = () => {
    navigate('/orders');
  };

  const handleOrderStatusClick = (payStatus) => {
    navigate(`/orders?tab=${payStatus}`);
  };

  const handleMenuItemClick = (item) => {
    if (item.path) {
      navigate(item.path);
    } else {
      console.log(`点击了${item.title}`);
    }
  };

  return (
    <div className="user-center">
      {/* 用户信息头部 - 毛玻璃效果 */}
      <div className="user-header">
        <div className="header-background"></div>
        <div className="header-content">
          <div className="user-info">
            <div className="avatar-container" onClick={handleEditUser}>
              <Avatar
                size="large"
                src={userInfo?.avatar}
                className="user-avatar"
                key={userInfo?.avatar}
              />
              <div className="level-badge">
                <Star />
              </div>
            </div>
            <div className="user-details">
              <div className="user-name"   key={userInfo?.name} onClick={handleEditUser}>{userInfo?.name}</div>
              <div className="user-level">
                <Star />
                <span>{userInfo?.level}</span>
              </div>
              <div className="level-progress">
                <div className="progress-info">
                  <span>距离{userInfo?.nextLevel}还需</span>
                  <span className="progress-text">
                    {userInfo?.levelProgress}%
                  </span>
                </div>
                <Progress
                  percent={userInfo?.levelProgress}
                  className="progress-bar"
                  showText={false}
                />
              </div>
            </div>
          </div>
          {/* <Button
            type="primary"
            size="small"
            className="edit-btn"
            icon={<Edit />}
          >
            编辑
          </Button> */}
        </div>
      </div>

      {/* 订单状态区域 */}
      <div className="order-section">
        <div className="order-header">
          <span className="order-title">我的订单</span>
          <span
            className="order-more"
            onClick={handleViewAllOrders}
          >
            查看全部订单
          </span>
        </div>
        <div className="order-status">
          {orderStatus.map((status, index) => (
            <div 
              key={index} 
              className="status-item"
              onClick={() => handleOrderStatusClick(status.payStatus)}
            >
              <div className="status-icon" style={{ color: status.color }}>
                {status.icon}
              </div>
              <div className="status-label">{status.label}</div>
              {/* {status.value !== '0' && (
                                <Badge value={status.value} className="status-badge" />
                            )} */}
            </div>
          ))}
        </div>
      </div>

      {/* 统计数据卡片 */}
      {/* <div className="stats-section">
        <div className="stats-grid">
          {statsData.map((stat, index) => (
            <div key={index} className="stat-card">
              <div
                className="stat-icon"
                style={{ backgroundColor: stat.color }}
              >
                {stat.icon}
              </div>
              <div className="stat-content">
                <div className="stat-value">{stat.value}</div>
                <div className="stat-label">{stat.label}</div>
              </div>
            </div>
          ))}
        </div>
      </div> */}

      {/* 功能菜单 */}
      <div className="menu-section">
        <div className="menu-list">
          {menuItems.map((item, index) => (
            <Cell
              extra={item.path ? <ArrowRight /> : null}
              key={index}
              title={
                <div style={{ display: 'flex', alignItems: 'center',gap: '10px' }}>
                  {item.icon} {item.title}
                </div>
              }
              onClick={() => handleMenuItemClick(item)}
            >
            </Cell>
          ))}
        </div>
      </div>



      {/* 退出登录确认对话框 */}
      <Dialog
        title="确认退出"
        content="确定要退出登录吗？"
        visible={showLogoutDialog}
        onConfirm={confirmLogout}
        onCancel={() => setShowLogoutDialog(false)}
        confirmText="确认"
        cancelText="取消"
      />

      {/* 编辑用户信息弹窗 */}
      <Popup
        visible={showEditDialog}
        position="center"
        onClose={() => setShowEditDialog(false)}
        style={{ 
          width: '90%', 
          maxWidth: '400px',
          borderRadius: '12px',
          padding: '0'
        }}
      >
        <div style={{ padding: '20px' }}>
          {/* 标题 */}
          <div style={{ 
            fontSize: '18px', 
            fontWeight: '600', 
            textAlign: 'center', 
            marginBottom: '20px',
            color: '#333'
          }}>
            编辑个人信息
          </div>

          {/* 头像编辑区域 */}
          <div style={{ textAlign: 'center', marginBottom: '24px' }}>
            <div style={{ position: 'relative', display: 'inline-block' }}>
              <Avatar
                size="large"
                src={editForm.avatar}
                style={{ width: '80px', height: '80px' }}
              />
              <div
                style={{
                  position: 'absolute',
                  bottom: '0',
                  right: '0',
                  width: '24px',
                  height: '24px',
                  backgroundColor: '#07c160',
                  borderRadius: '50%',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  cursor: 'pointer',
                  boxShadow: '0 2px 8px rgba(0,0,0,0.15)'
                }}
                onClick={handleAvatarSelect}
              >
                <Photograph style={{ color: 'white', fontSize: '12px' }} />
              </div>
            </div>
            <div style={{ marginTop: '8px', fontSize: '14px', color: '#666' }}>
              点击相机图标更换头像
            </div>
          </div>

          {/* 用户名输入 */}
          <div style={{ marginBottom: '24px' }}>
            <div style={{ marginBottom: '8px', fontSize: '14px', color: '#333', fontWeight: '500' }}>
              用户名称
            </div>
            <Input
              value={editForm.nickName}
              placeholder="请输入用户名称"
              onChange={(value) => handleFormChange('nickName', value)}
              maxLength={20}
            />
          </div>

          {/* 按钮区域 */}
          <div style={{ display: 'flex', gap: '12px' }}>
            <Button
              type="default"
              size="large"
              onClick={() => setShowEditDialog(false)}
              style={{ flex: 1 }}
            >
              取消
            </Button>
            <Button
              type="primary"
              size="large"
              loading={isUpdating}
              onClick={confirmUpdateUser}
              style={{ flex: 1 }}
            >
              保存
            </Button>
          </div>
        </div>
      </Popup>
    </div>
  );
};

export default UserView;
